package com.learn.springframework.v2.servlet;

import com.learn.springframework.annotation.Controller;
import com.learn.springframework.annotation.RequestMapping;
import com.learn.springframework.annotation.RequestParam;
import com.learn.springframework.context.ApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class DispatcherServlet extends HttpServlet {


    /**
     * 保存url和method的对应关系
     */
    private Map<String, Method> handlerMapping = new HashMap<String, Method>();
    /**
     * Ioc容器上下文
     */
    private ApplicationContext applicationContext = null;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 6、根据URL 委派给具体的调用方法
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception,Detail: " + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        String url = req.getRequestURI();
        String path = req.getContextPath();
        url = url.replaceAll(path, "").replaceAll("/+", "/");
        if (!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found !!!");
            return;
        }
        Method method = this.handlerMapping.get(url);
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 实参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] parameValues = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class) {
                parameValues[i] = req;
                continue;
            } else if (parameterType == HttpServletResponse.class) {
                parameValues[i] = resp;
                continue;
            } else if (parameterType == String.class) {
                Annotation[][] pa = method.getParameterAnnotations();
                for (int j = 0; j < pa.length; j++) {
                    for (Annotation a : pa[i]) {
                        if (a instanceof RequestParam) {
                            String paramName = ((RequestParam) a).value();
                            if (!"".equals(paramName.trim())) {
                                String value = Arrays.toString(parameterMap.get(paramName))
                                        .replaceAll("\\[|\\]", "")
                                        .replaceAll("\\s", ",");
                                parameValues[i] = value;
                            }
                        }
                    }
                }
            }
        }
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        method.invoke(this.applicationContext.getBean(beanName), parameValues);

    }

    /**
     * 初始化url 和method的一对一对应关系
     */
    private void doInitHandlerMapping() {
        if (this.applicationContext.getBeanDefinitionCount() == 0) {
            return;
        }
        for (String beanName : this.applicationContext.getBeanDefinitionNames()) {
            Object instance = applicationContext.getBean(beanName);
            Class<?> clazz = instance.getClass();
            if (!clazz.isAnnotationPresent(Controller.class)) {
                continue;
            }
            // 保存写在类上面@RequestMapping("/demo")
            String baseUrl = "";
            if (clazz.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                baseUrl = requestMapping.value();
            }
            // 默认获取所有的public方法
            for (Method method : clazz.getMethods()) {
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                String url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                handlerMapping.put(url, method);
                System.out.println("Mapped " + url + "," + method);
            }
        }
    }


    /**
     * 判断首字母是否大写
     *
     * @param c
     * @return boolean
     */
    public boolean isUpperCase(char c) {
        return c >= 65 && c <= 90;
    }


    private String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        // 利用了ASCII码，大写字母和小写字母相差32这个规律
        // 在java中，对char做算学运算，实际上就是对ASCII码做算学运算
        chars[0] += 32;
        return String.valueOf(chars);
    }


    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
//        doLoadConfig(config.getInitParameter("contextConfigLocation"));
//
//        // 2、扫描相关类
//        doScanner(contextConfig.getProperty("scanPackage"));
//        // ==========IoC功能======
//        // 3、初始化IoC容器，将扫描到的类进行实例化，缓存IoC容器中
//        doInstance();
//        // ==========DI功能======
//        // 4、完成依赖注入
//        doAutowired();
        applicationContext = new ApplicationContext(config.getInitParameter("contextConfigLocation"));
        // 5、初始化 HandlerMapping
        doInitHandlerMapping();

        System.out.println("Spring framework is init");

    }
}
